var salt = sessionStorage.getItem('usersalt');
layui.config({
    base: '../../../js/',
});

var app = new Vue({
    el: ".score",
    data: {
        multiSelect: [],
        radio: [],
        tfng: [],
        id: ''
    },
    updated: function () {

    }
})

layui.use(['form', 'layer', 'laydate', 'table', 'multiSelect'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        formSelects = layui.formSelects,
        table = layui.table;

    /*验证登录*/
    if (!sessionStorage.getItem('username')) {
        layer.msg('请先登录');
        setTimeout("top.location.href='../../../index.html'", 1000);
    }

    /*时间选择器*/
    laydate.render({
        elem: '#statdate',
        trigger: 'click'
    });

    laydate.render({
        elem: '#enddate',
        trigger: 'click'
    });

    /*筛选*/
    $('#seleCheck,#findscri').on('click', function () {
        getDangerList();
    });

    /*搜索*/
    $('#findscri').on('click', function () {
        var inptext = $('#inptext').val();
        var box = /\s/g;
        var param = inptext.replace(box, '');
    });
    var company;
    /*取出所有的单位*/
    function getAllDanwei() {
        $.ajax({
            url: url + 'baseEnt/getAllEnt',
            dataType: 'json',
            async: false,
            type: "POST",
            data: {},
            success: function (data) {
                $('#danwei').empty();
                if (data.code == 0) {
                    var list = data.data;
                    company = list;
                }

            },
            error: function (error) {
                console.log("获取失败");
            }
        });
    }

    getAllDanwei();

    /*------------tree.start------------*/
    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: zTreeOnCheck
        }
    };
    var zNodes = company;
    $.fn.zTree.init($("#danwei"), setting, zNodes);

    function getSydwVal() {
        var treeArr = [];
        var treeObj = $.fn.zTree.getZTreeObj("danwei");
        var nodes = treeObj.getCheckedNodes(true);
        for (var i = 0; i < nodes.length; i++) {
            treeArr.push(nodes[i].id); //获取选中节点的值
        }
        return treeArr;
    }

    $('#resclas').click(function () {
        $("body").trigger("click");
        $('#danwei').show();


    });

    function zTreeOnCheck(event, treeId, treeNode) {
        var nval = "";
        var treeObj = $.fn.zTree.getZTreeObj("danwei");
        var nodes = treeObj.getCheckedNodes(true);
        for (var i = 0; i < nodes.length; i++) {
            nval += nodes[i].name + ",";
        }
        $('#resclas').val(nval.substr(0, nval.length - 1));
    };
    /*------------tree.end------------*/

    var tableIns;

    function getDangerList(searchText) {
        var sydwArr = getSydwVal();
        if (!searchText) {
            searchText = null;
        }

        var types = [];
        var obj_type = document.getElementById("type");
        for (var i = 0; i < obj_type.options.length; i++) {
            if (obj_type.options[i].selected) {
                types.push(obj_type.options[i].value); // 收集选中项
            }
        }

        tableIns = table.render({
            elem: '#dangerList',
            method: 'post',
            url: url + 'questionUser/getQuestionUser',
            where: {
                Token: salt, //用户码
                examType: $("#type").val(),
                title: $("#inptext").val(),
                entId: sydwArr.toString(),
                startTime: $("#statdate").val(),
                endTime: $("#enddate").val(),
                questionStatus: '',
            },
            cellMinWidth: 60,
            page: true,
            height: "full-125",
            id: "dangerListTable",
            cols: [
                [{
                    type: "numbers",
                    width: 50,
                    title: "序号",
                },
                    {
                        field: 'type',
                        title: '试卷名称',
                        align: 'center',
                        templet: function (p) {
                            var str = "<div class='paperName paperinfo' id='" + p.id + "' userName='" + p.userName
                                + "' paperId='" + p.paperId + "' userId='" + p.userId + "' questionStatus='"
                                + p.questionStatus + "'"+" startTime=" + p.startTime +" endTime=" + p.endTime +">" + p.paperNaem + "</div>";
                            return str
                        }
                    },
                    {
                        field: '',
                        title: '总题数',
                        align: 'center',
                        templet: function (p) {
                            return "<div class='paperName'>" + p.questionNum + "</div>"
                        }
                    },
                    {
                        field: 'seat',
                        title: '总分值',
                        align: 'center',
                        templet: function (p) {
                            if (p.paperTotal) {
                                return "<div class='paperName'>" + p.paperTotal + "</div>";
                            } else {
                                return "<div class='paperName'></div>";
                            }
                        }
                    },
                    {
                        field: 'examType',
                        title: '考试类型',
                        align: 'center',
                        templet: function (p) {
                            if (p.examType == 0) {
                                return "<div class='paperName'>" + "模拟练习</div>";
                            } else if (p.examType == 1) {
                                return "<div class='paperName'>" + "班组测试</div>";
                            } else if (p.examType == 2) {
                                return "<div class='paperName'>" + "专项测试</div>";
                            }
                        }

                    },
                    {
                        field: 'numberNo',
                        title: '答题期限',
                        align: 'center',
                        templet: function (p) {
                            if (p.startTime) {
                                return "<div class='paperName'>" + initDate(p.startTime) + "至" + initDate(p.endTime) + "</div>";
                            } else {
                                return "<div class='paperName'>不限期</div>"
                            }
                        }
                    }, {
                    field: 'seat',
                    title: '答题状态',
                    align: 'center',
                    templet: function (p) {
                        if (p.examType == 0) {
                            return "<div class='paperName status'>模拟练习</div>";
                        } else {
                            if (p.questionStatus == 0) {
                                var date = new Date();
                                if (!p.startTime) {
                                    return "<div class='paperName status'>待作答</div>";
                                }
                                if (date < p.startTime) {
                                    return "<div class='paperName status" + "'>未开始</div>";
                                } else if (date > p.endTime) {
                                    return "<div class='paperName status'>已结束</div>";
                                } else {
                                    return "<div class='paperName status'>待作答</div>";
                                }
                            } else {
                                return "<div class='paperName status'>已完成</div>";
                            }
                        }
                    }
                },
                ]
            ],
            done: function (res, curr, count) {

            }
        });

    }

    getDangerList();

    //新增
    $(".addNews_btn").click(function () {
        $(".model").show();
    });


    //题库
    $(".subject_btn").click(function () {
        location.href = "../subject/subject.html"

    });

    //导出
    $(".export_btn").click(function () {

    });
    //导入
    $(".import_btn").click(function () {
        layer.open({
            type: 2,
            title: false,
            content: "page/404.html",
            area: ['700px', '300px']
        });
    });

})

$("body").on("click", ".paperName", function () {
    var $paperinfo = $(this).parents("tr").find(".paperinfo");
    var paperid = $paperinfo.attr("paperid");
    var username = $paperinfo.attr("username");
    var userId = $paperinfo.attr("userId");
    var questionStatus = $paperinfo.attr("questionStatus");
    var id = $paperinfo.attr("id");
    var Status = $(this).parents("tr").find(".status").text();
    if (Status == "模拟练习") {
        if (userId == salt) {
            location.href = '../question/question.html?id=' + paperid + "&userName=" + username;
        } else {
            layer.alert("当前为其他人的试卷，没有参加考试权限！", {
                btn: ['确定'] //按钮
            }, function (index) {
                layer.close(index);
            });
        }
        return
    }
    if (userId == salt) {
        if (questionStatus == 0) {
            var nowDate = new Date();
            var startTime = $paperinfo.attr("startTime");
            var endTime = $paperinfo.attr("endTime");
            if (nowDate < startTime || nowDate > endTime) {
                layer.alert("不可答题！", {
                    btn: ['确定'] //按钮
                }, function (index) {
                    layer.close(index);
                });
                return
            }

            location.href = '../question/question.html?id=' + paperid + "&userName=" + username;
        } else {
            getScore(id, paperid);
        }
    } else {
        if (questionStatus == 1) {
            getScore(id, paperid);
        } else {
            layer.alert("当前为其他人的试卷，没有参加考试权限！", {
                btn: ['确定'] //按钮
            }, function (index) {
                layer.close(index);
            });
        }
    }
})

function showDetail(checkId, userName) {
    location.href = '../question/question.html?id=' + checkId + "&userName=" + userName;
}

function initDate(data) {
    var time = new Date(data);
    var str = time.getFullYear() + "年" + (time.getMonth() + 1) + "月" + time.getDate() + "日";
    return str
}

$("body").on("click", ".score .title .layui-tab-close", function () {
    $(".score").hide();
})

function getScore(id, paperid) {
    $.post(url + "questionUser/getInfo", {id: id, Token: salt}, function (data) {
        if (data.code == 0) {
            var data = data.data;
            app.radio = JSON.parse(data.radio);
            app.multiSelect = JSON.parse(data.multiSelect);
            app.tfng = JSON.parse(data.tfng);
            app.id = data.id;
            app.paperid = paperid;
            console.log(data.radio)
            console.log(JSON.parse(data.radio))
            $(".score").show();
        }
    })
}

$("body").on("click", ".score ul li", function () {
    var id = $(this).attr("id");
    var questionId = $(this).attr("questionId");
    var paperid = $(this).attr("paperid");
    location.href = "../score/score.html?id=" + id + "&questionId=" + questionId + "&paperid=" + paperid;
})